package cn.iocoder.yudao.module.enterprise.service.company;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.enterprise.controller.admin.company.vo.*;
import cn.iocoder.yudao.module.enterprise.convert.company.EnterpriseCompanyConvert;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.company.EnterpriseCompanyDO;
import cn.iocoder.yudao.module.enterprise.dal.mysql.company.EnterpriseCompanyMapper;
import cn.iocoder.yudao.module.system.api.message.MessageApi;
import cn.iocoder.yudao.module.system.api.message.dto.MessageCreateReqDTO;
import cn.iocoder.yudao.module.system.api.permission.RoleApi;
import cn.iocoder.yudao.module.system.api.permission.dto.RoleDTO;
import cn.iocoder.yudao.module.system.api.sms.SmsCodeApi;
import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeUseReqDTO;
import cn.iocoder.yudao.module.system.api.tenant.TenantUserApi;
import cn.iocoder.yudao.module.system.api.tenant.dto.TenantCreateVo;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.api.user.dto.UserUpateReqDTO;
import cn.iocoder.yudao.module.system.api.userRole.AdminUserRoleApi;
import cn.iocoder.yudao.module.system.api.userRole.dto.UserRoleDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.userChangeMobileRecordrecord.UserChangeMobileRecordrecordDO;
import cn.iocoder.yudao.module.system.dal.mysql.userChangeMobileRecordrecord.UserChangeMobileRecordrecordMapper;
import lombok.Synchronized;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.module.enterprise.enums.ErrorCodeConstants.*;

/**
 * 企业信息 Service 实现类
 *
 * @author 谭万全
 */
@Service
@Validated
public class EnterpriseCompanyServiceImpl implements EnterpriseCompanyService {

    @Resource
    private EnterpriseCompanyMapper enterpriseCompanyMapper;
    @Resource
    private UserChangeMobileRecordrecordMapper userChangeMobileRecordrecordMapper;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private TenantUserApi tenantUserApi;
    @Resource
    private SmsCodeApi smsCodeApi;

    @Resource
    private RoleApi roleApi;
    @Resource
    private AdminUserRoleApi adminUserRoleApi;

    @Resource
    private MessageApi messageApi;
    @Override
    public Long createCompany(CompanyCreateReqVO createReqVO) {
        // 插入
        EnterpriseCompanyDO company = EnterpriseCompanyConvert.INSTANCE.convert(createReqVO);
        enterpriseCompanyMapper.insert(company);
        // 返回
        return company.getId();
    }

    @Override
    public void updateCompany(CompanyUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateCompanyExists(updateReqVO.getId());
        // 更新
        EnterpriseCompanyDO updateObj = EnterpriseCompanyConvert.INSTANCE.convert(updateReqVO);
        enterpriseCompanyMapper.updateById(updateObj);
    }

    @Override
    public void updateCompanyIsRealName(Long id, String isRealName) {
        // 校验存在
        this.validateCompanyExists(id);
        // 更新
        EnterpriseCompanyDO updateObj =new EnterpriseCompanyDO();
        updateObj.setId(id);
        updateObj.setIsRealName(isRealName);
        enterpriseCompanyMapper.updateById(updateObj);
    }

    @Override
    public void deleteCompany(Long id) {
        // 校验存在
        this.validateCompanyExists(id);
        // 删除
        enterpriseCompanyMapper.deleteById(id);
    }

    private void validateCompanyExists(Long id) {
        if (enterpriseCompanyMapper.selectById(id) == null) {
            throw exception(COMPANY_NOT_EXISTS);
        }
    }

    @Override
    public EnterpriseCompanyDO getCompany(Long id) {
        return enterpriseCompanyMapper.selectById(id);
    }

    @Override
    public EnterpriseCompanyDO getCompanyByphone(String phone) {
        return  enterpriseCompanyMapper.selectOne("phone_number",phone);
    }

    @Override
    public EnterpriseCompanyDO getCompany(String cardNo, String phone, String userName) {
        return enterpriseCompanyMapper.selectOne(EnterpriseCompanyDO::getCardNo,cardNo,EnterpriseCompanyDO::getPhoneNumber,phone,EnterpriseCompanyDO::getApplyUserName,userName);
    }

    @Override
    public EnterpriseCompanyDO getCompanyByLoginUser(Long companyId) {
        return enterpriseCompanyMapper.selectOne("id",companyId);
    }

    @Override
    public List<EnterpriseCompanyDO> getCompanyList(Collection<Long> ids) {
        return enterpriseCompanyMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<EnterpriseCompanyDO> getCompanyPage(CompanyPageReqVO pageReqVO) {
        return enterpriseCompanyMapper.selectPage(pageReqVO);
    }

    @Override
    public List<EnterpriseCompanyDO> getCompanyList(CompanyExportReqVO exportReqVO) {
        return enterpriseCompanyMapper.selectList(exportReqVO);
    }
    @Override
    @Synchronized
    @TenantIgnore
    @Transactional(rollbackFor = Exception.class)
    public EnterpriseCompanyDO applyAuthenticationCompany(@Valid CompanyCreateReqVO createReqVO) {
        List<String> list=new ArrayList<>();
        list.add("authorized");
        list.add("unauthorized");
        List<EnterpriseCompanyDO> enterpriseCompanyDO=enterpriseCompanyMapper.isExistence(createReqVO.getCreditCode(),list);
        if(enterpriseCompanyDO!=null&&enterpriseCompanyDO.size()>0){
            throw exception(TENANT_COMPANY_AYTHORIZED_ISEXISTS);
        }
        EnterpriseCompanyDO company=enterpriseCompanyMapper.selectOne("phone_number",createReqVO.getPhoneNumber());
        if (company == null) {
            EnterpriseCompanyDO insetcompany=EnterpriseCompanyConvert.INSTANCE.convert(createReqVO);
            insetcompany.setAuthorizedStatus("authorizeding");
            TenantUtils.execute(SecurityFrameworkUtils.getLoginUser().getTenantId(), () -> {
                //执行创建企业insert
                 enterpriseCompanyMapper.insert(insetcompany);
                //创建企业
                UserUpateReqDTO userUpateReqDTO=new UserUpateReqDTO();
                userUpateReqDTO.setId(SecurityFrameworkUtils.getLoginUserId());
                userUpateReqDTO.setCompanyId(insetcompany.getId());
                userUpateReqDTO.setNickname(insetcompany.getApplyUserName());
                userUpateReqDTO.setRemark(insetcompany.getJob());
                userUpateReqDTO.setEmail(insetcompany.getEmail());
                adminUserApi.updateUser(userUpateReqDTO);
            });
            String title="身份认证审核中";
            String message="您好，平台已收到来自"+insetcompany.getCompanyName()+"的身份认证提交审核，进行审核中";
            List<Long> ids= adminUserApi.getUserIdsByTenant(2l);
            for (Long id:ids) {
                sendmessage(1l,id,title,message);
            }

            return insetcompany;
        }else {
            EnterpriseCompanyDO updatecompany=EnterpriseCompanyConvert.INSTANCE.convert(createReqVO);
            updatecompany.setId(company.getId());
            updatecompany.setAuthorizedStatus("authorizeding");
            enterpriseCompanyMapper.updateById(updatecompany);
            return updatecompany;
        }


    }
    @Async
    void sendmessage(Long type, Long id, String title, String messageText){
        MessageCreateReqDTO messageCreateReqVO=new MessageCreateReqDTO();
        messageCreateReqVO.setPhone("");
        messageCreateReqVO.setType(type);
        messageCreateReqVO.setStatus("5");
        messageCreateReqVO.setUserId(id);
        messageCreateReqVO.setStudentName("系统管理员");
        messageCreateReqVO.setRemark(messageText);
        messageCreateReqVO.setTitle(title);
        messageApi.sendMessage(messageCreateReqVO);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePhone(CompanyUpdatePhoneReqVO updateReqVO) {
        SmsCodeUseReqDTO smsCodeUseReqDTO=new SmsCodeUseReqDTO();
        smsCodeUseReqDTO.setMobile(updateReqVO.getNewMobile());
        smsCodeUseReqDTO.setScene(updateReqVO.getScene());
        smsCodeUseReqDTO.setCode(updateReqVO.getCode());
        smsCodeUseReqDTO.setUsedIp(getClientIP());
        smsCodeApi.useSmsCode(smsCodeUseReqDTO);
        LoginUser user=SecurityFrameworkUtils.getLoginUser();
        AdminUserRespDTO adminUserRespDTO=adminUserApi.getUser(user.getId());
        AdminUserRespDTO newUser=adminUserApi.getNoTenantUser(updateReqVO.getNewMobile());
        if(newUser!=null){
            throw exception(USER_NEW_PHONE_IS_EXISTS);
        }
        List<UserRoleDTO> userRoleDTO=adminUserRoleApi.getUserRoleByUserId(user.getId());
        Set<String> roleCodes=new HashSet<>();
        for (UserRoleDTO userRole:userRoleDTO){
            RoleDTO roleDTO= roleApi.getRole(userRole.getRoleId());
            roleCodes.add(roleDTO.getCode());
        }
        EnterpriseCompanyDO enterpriseCompanyDO=this.getCompanyByLoginUser(adminUserRespDTO.getCompanyId());
        user.setRoleCodes(roleCodes);
        if(adminUserApi.isAdminUser(user)){//判断是否是企业管理员
            UserChangeMobileRecordrecordDO userChangeMobileRecordrecordDO=new UserChangeMobileRecordrecordDO();
            userChangeMobileRecordrecordDO.setOldMobile(user.getUsername());
            userChangeMobileRecordrecordDO.setNewMobile(updateReqVO.getNewMobile());
            userChangeMobileRecordrecordDO.setCompanyName(enterpriseCompanyDO.getCompanyName());
            userChangeMobileRecordrecordDO.setNickname(adminUserRespDTO.getNickname());
            userChangeMobileRecordrecordDO.setDept(user.getDeptName());
            userChangeMobileRecordrecordDO.setUsername(user.getUsername());
            userChangeMobileRecordrecordDO.setUserId(user.getId());
            userChangeMobileRecordrecordDO.setDataUrl(updateReqVO.getDataUrl());
            userChangeMobileRecordrecordDO.setUserId(user.getId());
            userChangeMobileRecordrecordDO.setTenantId(user.getTenantId());
            userChangeMobileRecordrecordDO.setDepartment(enterpriseCompanyDO.getDept());
            userChangeMobileRecordrecordDO.setCompanyId(enterpriseCompanyDO.getId());

            userChangeMobileRecordrecordDO.setApplyUserName(updateReqVO.getApplyUserName());
            userChangeMobileRecordrecordDO.setCardNo(updateReqVO.getCardNo());
            userChangeMobileRecordrecordDO.setAuthStatus(updateReqVO.getAuthStatus());
            userChangeMobileRecordrecordDO.setAuthenticationFrontPictureUrl(updateReqVO.getAuthenticationFrontPictureUrl());
            userChangeMobileRecordrecordDO.setAuthenticationBackPictureUrl(updateReqVO.getAuthenticationBackPictureUrl());
            userChangeMobileRecordrecordMapper.insert(userChangeMobileRecordrecordDO);
            enterpriseCompanyDO.setAuthorizedStatus("changeing");
            //发送给企业
            String title=enterpriseCompanyDO.getCompanyName()+"-"+user.getUsername()+"：企业更换手机号审核";
            String message="您好，平台已收到来自"+enterpriseCompanyDO.getCompanyName()+"的更换手机号提交审核，进行审核";
            sendmessage(1l,user.getId(),title,message);
            //发送给运营
            title="企业更换手机号提交审核";
            message="您好，收到来自"+enterpriseCompanyDO.getCompanyName()+"的更换手机号提交审核，提交人："+user.getUsername()+"，提交人手机号："+updateReqVO.getOldMobile()+",请查收";
            List<Long> ids= adminUserApi.getUserIdsByTenant(2l);
            for (Long id1:ids) {
                sendmessage(1l,id1,title,message);
            }


        }
//        else{//不是企业管理员直接更改
//            adminUserApi.updateUsersPhone(user.getId(),updateReqVO.getNewMobile(),0);
//            enterpriseCompanyDO.setPhoneNumber(updateReqVO.getNewMobile());
//            enterpriseCompanyDO.setApplyUserName(updateReqVO.getApplyUserName());
//        }
//        enterpriseCompanyDO.setCardNo(updateReqVO.getCardNo());
//        enterpriseCompanyDO.setAuthenticationFrontPictureUrl(updateReqVO.getAuthenticationFrontPictureUrl());
//        enterpriseCompanyDO.setAuthenticationBackPictureUrl(updateReqVO.getAuthenticationBackPictureUrl());
//        enterpriseCompanyMapper.updateById(enterpriseCompanyDO);

    }

    @Override
    public Boolean checkCreditCode(String creditCode) {

        EnterpriseCompanyDO enterpriseCompanyDO=enterpriseCompanyMapper.selectOne("credit_code",creditCode,"deleted",0);
        if(enterpriseCompanyDO==null){
            return true;
        }
        return false;
    }

    @Override
    public Boolean isAuthentication(Long tenantId) {
        EnterpriseCompanyDO enterpriseCompanyDO=enterpriseCompanyMapper.selectOne("tenant_id","tenantId");
        if(enterpriseCompanyDO.getAuthorizedStatus()!=null&&enterpriseCompanyDO.getAuthorizedStatus().equals("authorized")){
            return  true;
        }
        return false;
    }


}
